import 'dart:convert';

import 'package:appinio_swiper/controllers.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:get/get.dart';
import 'package:memorize_words/db/db_serializer.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:permission_handler_platform_interface/permission_handler_platform_interface.dart';
import 'dart:convert' as convert;
import '../../../../db/db_helper.dart';
import '../../../../store/setting_store.dart';
import '../../../routes/app_pages.dart';

class HomeController extends GetxController with StateMixin<Map> {
  RxMap bookForm = {}.obs;
  RxMap wordForm = {}.obs;
  RxInt bookSelected = 0.obs;
  RxInt wordSelected = 0.obs;
  SettingStore _settingStore = SettingStore();

  GlobalKey<FormState> helpTextKey = GlobalKey<FormState>();
  TextEditingController val = TextEditingController();
  TextEditingController desc = TextEditingController();

  getHelpText() async {
    if (wordForm.value["helpText"] != null && wordForm.value["helpText"] != '' && wordForm.value["helpText"] != 'null'){
      return json.decode(wordForm.value["helpText"]);
    } else {
      wordForm.value["helpText"] = json.encode({
        'default': {"val": "","desc": ""},
        'self': []
      });
      return {
        'default': {"val": "","desc": ""},
        'self': []
      };
    }
  }
  reStr(String oldStr){
    String newStr = oldStr.replaceAll("'", "''");
    return newStr;
  }
  updateWord() async {
    var newWord = json.decode(json.encode(wordForm.value));
    newWord['belong'] = reStr(newWord['belong']);
    newWord['name'] = reStr(newWord['name']);
    newWord['ukphone'] = reStr(newWord['ukphone']);
    newWord['usphone'] = reStr(newWord['usphone']);
    newWord['trans'] = reStr(newWord['trans']);
    newWord['syno'] = reStr(newWord['syno']);
    newWord['relWord'] = reStr(newWord['relWord']);
    newWord['sentence'] = reStr(newWord['sentence']);
    newWord['phrase'] = reStr(newWord['phrase']);
    newWord['exam'] = reStr(newWord['exam']);
    newWord['helpText'] = reStr(newWord['helpText']);
    newWord['soundText'] = reStr(newWord['soundText']);
    // print(newWord);
    var updateRes = await localData.updateWords(newWord);
  }

  getWord() async {
    bookSelected.value = await _settingStore.getBookSelected();
    wordSelected.value = await _settingStore.getWordSelected();
    wordForm.value = {};
    print("bookSelected--------${bookSelected.value}");
    print("wordSelected--------${wordSelected.value}");
    if (bookSelected.value != 0) {
      bookForm.value = await localData.getBooksById(bookSelected.value);
      // print("${wordSelected.value+1}/${bookForm.value['num']}");
      var res = await localData.getCurrentWord(bookSelected.value,wordSelected.value);
      if (res.isNotEmpty) {
        wordForm.value = res;
        // print("------->");
        // print(wordForm.value);
        change(wordForm, status: RxStatus.success());
      } else {
        if (wordSelected.value != 0){
          await _settingStore.setWordSelected(0);
          Fluttertoast.showToast(
            msg: "没有啦！",
            toastLength: Toast.LENGTH_SHORT,
            gravity: ToastGravity.CENTER,
            backgroundColor: Colors.red,
            textColor: Colors.white,
            fontSize: 16.0,
          );
          onInit();
        } else {
          Get.offNamed('/books');
          Fluttertoast.showToast(
            msg: "请先选择词典再进行操作！",
            toastLength: Toast.LENGTH_SHORT,
            gravity: ToastGravity.CENTER,
            backgroundColor: Colors.red,
            textColor: Colors.white,
            fontSize: 16.0,
          );
        }
      }
    } else {
      Get.offNamed('/books');
      Fluttertoast.showToast(
        msg: "请先选择词典再进行操作！",
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.CENTER,
        backgroundColor: Colors.red,
        textColor: Colors.white,
        fontSize: 16.0,
      );
    }
  }

  // 扫一扫
  String qrCode = '';
  void handleScan() async {
    await [Permission.camera].request();
    await Get.toNamed(Routes.QR_SCAN)?.then((value) async {
      if (value == null) return;
      qrCode = value;
      // Fluttertoast.showToast(
      //   msg: qrCode.toString(),
      //   toastLength: Toast.LENGTH_SHORT,
      //   gravity: ToastGravity.CENTER,
      //   backgroundColor: Colors.black12,
      //   textColor: Colors.black87,
      //   fontSize: 16.0,
      // );
      showQR(qrCode);
    });
  }
  void showQR(String qrCode) async {
    TextEditingController qrCodeText = TextEditingController();
    qrCodeText.text = qrCode;
    Get.defaultDialog(
      title: '扫描内容',
      radius: 10.0,
      barrierDismissible: false,
      content: Container(
        padding: const EdgeInsets.all(16.0),
        child: Padding(
          padding: const EdgeInsets.fromLTRB(35.0, 5.0, 35.0, 0.0),
          child: TextFormField(
            autovalidateMode: AutovalidateMode.disabled,
            controller: qrCodeText,
            style: const TextStyle(fontSize: 20.0),
            maxLength: 16,
            decoration: const InputDecoration(
              hintText: '扫描内容',
              border: InputBorder.none,
              counter: SizedBox(),
            ),
          ),
        ),
      ),
      cancel: MaterialButton(
        color: Colors.black87,
        textColor: Colors.white,
        child: const Text('确认', style: TextStyle(fontSize: 18.0,fontWeight: FontWeight.w600)),
        onPressed: () {
          Get.back();
        },
      ),
    );
  }

  /// 跳转编辑界面 按需要修改路由
  toEditPage() {
    Get.toNamed('/edit-help-text', arguments: wordForm.value)?.then((value) async {
      onInit();
    });
  }


  @override
  Future<void> onInit() async {
    // swiperController = AppinioSwiperController();
    await getWord();
    super.onInit();
  }

  @override
  void onReady() {
    super.onReady();
  }

  @override
  void onClose() {
    super.onClose();
  }
}
